package com.erps.db;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import redis.clients.jedis.Jedis;

import com.erps.CommonUtils.ValueType;

public class KVDB {
	public final static String KV_HOST = "KV_HOST";
	public final static String KV_HOST_DEFVAL = "127.0.0.1";

	public final static String KV_PORT = "KV_PORT";
	public final static int KV_PORT_DEFVAL = 6379;
	private static Jedis vRedis = null;

	public static int WriteStr(String cKeyName, int iKeyValue) {
		return WriteStr(cKeyName, String.valueOf(iKeyValue));
	}

	public static Jedis getRedis() {
		if ((vRedis == null) || (!vRedis.isConnected())) {
			String cHost;
			try {
				cHost = ReadString(KV_HOST, KV_HOST_DEFVAL);
			} catch (Exception e) {
				cHost = KV_HOST_DEFVAL;
			}

			int iPort = ReadInt(KV_PORT, KV_PORT_DEFVAL);
			return new Jedis(cHost, iPort);
		} else {
			return vRedis;
		}
	}

	public static String ReadString(String KeyName, String DefValue) {
		InputStream fis = (new KVDB()).getClass().getResourceAsStream(
				"/config.properties");
		Properties prop = new Properties();
		try {
			prop.load(fis);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (prop.get(KeyName) != null)
			return prop.getProperty(KeyName);
		else
			return DefValue;

	}

	public static int ReadInt(String KeyName, int iValue) {
		String cv = ReadString(KeyName, String.valueOf(iValue));
		try {
			return Integer.parseInt(cv);
		} catch (Exception ex) {
			return iValue;
		}
	}

	public static int WriteStr(String cKeyName, String cKeyValue) {
		int iCode = -1;
		Jedis redis = getRedis();
		if (redis == null) {
			iCode = ValueType.FAILURE;
		} else {
			try {
				redis.set(cKeyName, cKeyValue);
				iCode = ValueType.SUCCESS;
			} catch (Exception ex) {
				iCode = ValueType.FAILURE;
			} finally {
				try {
					redis.close();
					redis = null;
				} catch (Exception ex) {
					;
				}
			}
		}
		return iCode;
	}

	public static String ReadStr(String cKeyName, String cKeyValue) {
		Jedis redis = getRedis();
		try {
			cKeyValue = redis.get(cKeyName);
			return cKeyValue;
		} catch (Exception ex) {
			return cKeyValue;
		} finally {
			try {
				redis.close();
				redis = null;
			} catch (Exception ex) {
				;
			}
		}
	}
}
